package com.zhupf.binaryTree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author zhupf
 * @date 2023年12月01日 9:18
 * @Description
 *  230. 二叉搜索树中第K小的元素
 */
public class KthSmallest {

    public int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> stk = new LinkedList<>();
        int result = 0;
        while ((root != null || !stk.isEmpty()) && k >0){
            while (root != null){
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            result = root.val;
            k--;
            root = root.right;
        }
        return result;
    }

}
